<template>
  <div style="position: relative" class="app-container">
    <!-- 班次设置 -->
    <div style="padding: 20px 20px 0px 20px">
      <h6>班次设置</h6>

      <el-form
        ref="form"
        :model="timeParams"
        label-width="100px"
        label-position="left"
        style="margin-top: 35px"
      >
        <el-form-item label="白班时间">
          <el-time-picker
            value-format="HH:mm:ss"
            is-range
            v-model="timeParams.dayTime"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>

        <el-form-item
          label="白班员工设置"
          class="timeSetting"
          style="padding: 0; display: flex; flex-direction: column"
        >
          <el-checkbox-group v-model="dayShiftUserIds">
            <el-checkbox-button
              v-for="city in staffList"
              :label="city.userId"
              :key="city.userId"
              >{{ city.nickName }}</el-checkbox-button
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="夜班时间">
          <el-time-picker
            is-range
            value-format="HH:mm:ss"
            v-model="timeParams.nightTime"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>

        <el-form-item
          label="夜班员工设置"
          class="timeSetting"
          style="padding: 0; display: flex; flex-direction: column"
        >
          <el-checkbox-group v-model="nightShiftUserIds">
            <el-checkbox-button
              v-for="city in staffList"
              :label="city.userId"
              :key="city.userId"
              >{{ city.nickName }}</el-checkbox-button
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <hr />
    <div style="padding: 10px 20px 0 20px">
      <el-switch
        @change="handleChangeIsAuto"
        :value="autoData.isAuto"
        active-text="自动班结"
      >
      </el-switch>
    </div>
    <!-- 开启自动班结后的选择油站，每天班结时间设置 -->
    <div class="station_box" ref="stationBox" v-if="autoData.isAuto">
      <template>
        <el-form
          v-for="(item, index) in autoData.automaticClassInfos"
          :rules="automaticClassInfosRules"
          :key="index"
          ref="form"
          :model="item"
          label-width="80px"
          label-position="left"
          size="mini"
        >
          <div class="station_item">
            <div class="left_item">
              <p class="title">选择油站</p>
              <el-form-item label="油站名称" prop="stationId">
                <el-select v-model="item.stationId" placeholder="请选择">
                  <el-option
                    v-for="item in stationList"
                    :key="item.stationId"
                    :label="item.stationName"
                    :value="item.stationId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <p class="title">每天班结时间设置</p>
              <el-form-item
                label-width="100px"
                v-for="(dateItem, dateIndex) in item.dateList"
                :key="dateIndex"
              >
                <span class="t" slot="label">班结时间{{ dateIndex + 1 }}</span>
                <el-time-select
                  placeholder="请选择"
                  v-model="dateItem.time"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '23:00',
                  }"
                >
                </el-time-select>
                <el-button
                  v-if="(item.dateList&&item.dateList.length) === dateIndex + 1"
                  class="ml8"
                  type="primary"
                  icon="el-icon-plus"
                  circle
                  @click="handleAddDate(index, dateIndex)"
                ></el-button>
                <el-button
                  class="ml8"
                  v-if="dateIndex > 0"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="handleDeleteDate(index, dateIndex)"
                ></el-button>
              </el-form-item>
            </div>
            <div class="right_item">
              <el-button
                v-if="
                  stationLen > 1 &&
                  (autoData.automaticClassInfos&&autoData.automaticClassInfos.length) === index + 1
                "
                type="primary"
                size="mini"
                @click="handleAddStation"
                >添加</el-button
              >
              <el-button
                v-if="index >= 0 && (autoData.automaticClassInfos&&autoData.automaticClassInfos.length) > 1"
                type="danger"
                size="mini"
                @click="handleDeleteStation(index)"
                >删除</el-button
              >
            </div>
          </div>
        </el-form>
      </template>
    </div>
    <el-divider></el-divider>
    <!-- 首页时间查询设置 -->
    <div class="timeSetting">
      <p>首页时间查询设置</p>
      <el-checkbox-group
        v-model="homePageTimeSetting"
        @change="handleHomePageTimeSetting"
        size="large"
        style="margin-top: 35px"
      >
        <el-checkbox-button label="homeAll" key="homeAll">
          全部
        </el-checkbox-button>
        <br />
        <el-checkbox-button label="homeToday" key="homeToday" :disabled="true">
          今天
        </el-checkbox-button>
        <el-checkbox-button label="homeYesterday" key="homeYesterday">
          昨天
        </el-checkbox-button>
        <el-checkbox-button label="homeWeek" key="homeWeek">
          本周
        </el-checkbox-button>
        <el-checkbox-button label="homeMonth" key="homeMonth">
          本月
        </el-checkbox-button>
        <el-checkbox-button label="homeCustom" key="homeCustom">
          自定义
        </el-checkbox-button>
      </el-checkbox-group>
    </div>
    <el-divider></el-divider>
    <!-- 员工账号首页数据展示 -->
    <div class="timeSetting">
      <p>员工账号首页数据展示</p>
      <div style="margin-top: 35px">
        <el-radio v-model="radio" label="0">按当日</el-radio>
        <el-radio v-model="radio" label="1">按班结</el-radio>
      </div>
    </div>
    <div class="bottom_box">
      <el-button type="primary" @click="handleSubmit" style="margin-top: 35px"
        >保存</el-button
      >
    </div>
  </div>
</template>
<script>
import { getEnterpriseStationList } from "@/api/dept";
import {
  setAutomaticClass,
  getAutomaticClass,
  updateClassTime,
  getDayClassTime,
} from "@/api/station/order";
import {
  homePageTimeSettingApi,
  getHomePageTimeSettingListApi,
  getHomePageBanjieSettingApi,
  editHomePageBanjieSettingApi,
  staffQuery,
} from "@/api/system/permissionSetting";
import { error } from "highcharts";
export default {
  data() {
    return {
      autoData: {
        isAuto: false,
        automaticClassInfos: [],
      },
      stationList: [],
      automaticClassInfosRules: {
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
      },

      // 员工
      staffList: [],
      // 白天班结员工
      dayShiftUserIds: [],
      // 晚上班结员工
      nightShiftUserIds: [],

      timeParams: {
        dayTime: null,
        nightTime: null,
      },
      homePageTimeOption: [
        "homeAll",
        "homeToday",
        "homeYesterday",
        "homeWeek",
        "homeMonth",
        "homeCustom",
      ],
      // 首页时间查询设置
      homePageTimeSetting: [
        "homeAll",
        "homeToday",
        "homeYesterday",
        "homeWeek",
        "homeMonth",
        "homeCustom",
      ],
      isAll: true, // 控制时间设置是否选择全部
      homeTimeId: null, // 用户更新首页时间查询时传的id
      radio: "1",
    };
  },
  computed: {
    stationLen() {
      let list = [];
      if (this.stationList&&this.stationList.length > 0) {
        list = this.stationList.filter((f) => f.status === "1");
      }
      return list.length;
    },
  },
  created() {
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getData(this.presentEnterprise.enterpriseId);
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
    
    this.getDayClassTimeInfo();
    
    this.getHomePageTimeSetting();
    
    this.getStaffQuery();
  },
  methods: {
    // 白班夜班员工
    getStaffQuery() {
      const enterpriseId = this.presentEnterprise?.enterpriseId
        ? this.presentEnterprise.enterpriseId
        : null;
      const stationId = this.$store.state.user.stationId
        ? this.$store.state.user.stationId
        : null;

      const data = {
        page: 1,
        pageSize: 999,
        enterpriseId,
        stationId,
      };
      staffQuery(data)
        .then((res) => {
          this.staffList = res.rows;
        })
        .catch(() => {
          this.staffList = [];
        });
    },
    // 首页时间查询设置选中值发生改变时，选择了全部，则其他的按钮要选中
    handleHomePageTimeSetting(list) {
      if (list.includes("homeAll")) {
        this.homePageTimeSetting = [
          "homeAll",
          "homeToday",
          "homeYesterday",
          "homeWeek",
          "homeMonth",
          "homeCustom",
        ];
        this.msgInfo("已选择全部");
      }
    },
    // 获取首页时间查询设置
    async getHomePageTimeSetting() {
      const userId = this.$store.state.user.userId;
      const res = await getHomePageTimeSettingListApi({ userId: userId });
      this.homeTimeId = res.data.id;
      let list = [];
      // 已选中按钮的数据回显 , 如果全部按钮被选中了，则其他按钮要被选中
      if (res.data.homeAll === "1") {
        list = [
          "homeAll",
          "homeToday",
          "homeYesterday",
          "homeWeek",
          "homeMonth",
          "homeCustom",
        ];
      } else {
        // 否则把选中的按钮筛选出来
        for (let item in res.data) {
          if (res.data[item] === "1") {
            list.push(item);
          }
        }
      }
      this.getHomePageBanjieSetting();
      this.homePageTimeSetting = list;
    },
    // 获取首页员工账号数据展示查询
    async getHomePageBanjieSetting() {
      const res = await getHomePageBanjieSettingApi();
      if (res.code == 200) {
        if (res.data&&res.data.length < 2) {
          this.radio = res.data[0];
        } else {
          this.radio = undefined;
        }
      }
    },
    // 查询班次时间
    getDayClassTimeInfo() {
      getDayClassTime().then((res) => {
        if (res) {
          // 白天班结员工
          if (res.dayShiftUserIds) {
            const dayShiftUserIds = res.dayShiftUserIds&& res.dayShiftUserIds.split(",");
            this.dayShiftUserIds = dayShiftUserIds.map((item) => {
              return parseInt(item);
            });
          } else {
            this.dayShiftUserIds = [];
          }
          // 晚上班结员工
          if (res.nightShiftUserIds) {
            const nightShiftUserIds = res.nightShiftUserIds&&res.nightShiftUserIds.split(",");
            this.nightShiftUserIds = nightShiftUserIds.map((item) => {
              return parseInt(item);
            });
          } else {
            this.nightShiftUserIds = [];
          }
          
          const dayTimeArray = [res.dayShiftStartTime||'', res.dayShiftEndTime||''];
          const nightTimeArray = [
            res.nightShiftStartTime||'',
            res.nightShiftEndTime||'',
          ];
          this.timeParams.dayTime = dayTimeArray;
          this.timeParams.nightTime = nightTimeArray
        }
      });
    },
    // 辅助函数，将时间字符串转换为以秒为单位的时间
    getTimeInSeconds(timeString) {
      if(timeString){ 
        const [hours, minutes, seconds] = timeString&&timeString.split(":");
      return hours * 3600 + minutes * 60 + seconds;
      }
      
    },
    // 查询油站
    getStationList(val) {
      getEnterpriseStationList({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
    getData(enterpriseId) {
      getAutomaticClass({ id: enterpriseId }).then((res) => {
        res.data.isAuto = !!res.data.isAuto;
        if (res.data.automaticClassInfos) {
          res.data.automaticClassInfos.forEach((item) => {
            item.dateList = [];
            item.knotTimes.forEach((timeItem) => {
              let data = {
                time: timeItem,
              };
              item.dateList.push(data);
            });
          });
        }

        this.autoData = res.data;
        if (this.autoData.automaticClassInfos === null) {
          this.autoData.automaticClassInfos = [];
        }
      });
    },
    // 保存
    handleSubmit() {
      // 自动班结的数据校验
      let isDate = null;
      for (let i = 0; i < (this.autoData.automaticClassInfos&&this.autoData.automaticClassInfos.length); i++) {
        let item = this.autoData.automaticClassInfos[i];
        isDate = item.dateList.every((e) => e.time);
        if (!isDate) {
          break;
        }
      }
      if (!isDate && this.autoData.isAuto) {
        return this.$message.error("班结时间不能为空");
      }

      // 首页时间查询设置参数 ： 把选中的按钮值为1 ，未选中的按钮为0
      const homeParams = {};
      const homePageTimeSetting = this.homePageTimeSetting;
      this.homePageTimeOption.forEach((item) => {
        if (homePageTimeSetting.includes(item)) {
          homeParams[item] = "1";
        } else {
          homeParams[item] = "0";
        }
      });
      homeParams.userId = this.$store.state.user.userId;
      homeParams.id = this.homeTimeId;

      this.$confirm("是否确认保存班结设置相关数据", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
        // 设置班次
        let params = {
          dayShiftEndTime: null,
          dayShiftStartTime: null,
          nightShiftEndTime: null,
          nightShiftStartTime: null,
          dayShiftUserIds: this.dayShiftUserIds.join(","),
          nightShiftUserIds: this.nightShiftUserIds.join(","),
        };

        if (
          !(
            (!this.timeParams.dayTime && !this.timeParams.nightTime) ||
            (!!this.timeParams.dayTime && !!this.timeParams.nightTime)
          )
        ) {
          return this.$message.warning("白夜班不能单独设置");
        }
        if (this.timeParams.dayTime && this.timeParams.nightTime) {
          params.dayShiftStartTime = this.timeParams.dayTime[0];
          params.dayShiftEndTime = this.timeParams.dayTime[1];
          params.nightShiftStartTime = this.timeParams.nightTime[0];
          params.nightShiftEndTime = this.timeParams.nightTime[1];
          if (
            this.getTimeInSeconds(params.dayShiftStartTime) <
              this.getTimeInSeconds(params.nightShiftEndTime) &&
            this.getTimeInSeconds(params.dayShiftEndTime) >
              this.getTimeInSeconds(params.nightShiftStartTime)
          ) {
            // 时间段存在交集
            return this.$message.warning("时间段存在交集");
          }
        }

        // 更新班次设置接口
        if(!params.dayShiftEndTime){
          params.dayShiftEndTime=null
        }
        if(!params.dayShiftStartTime){
          params.dayShiftStartTime=null
        }
        if(!params.nightShiftStartTime){
          params.nightShiftStartTime=null
        }
        if(!params.nightShiftEndTime){
          params.nightShiftEndTime=null
        }
        if (this.$store.state.user.userLevel !== null) {
          updateClassTime(params).then(res => {
            if (res && res.code == 200) {
              this.$message.success(res&&res.msg);
            } else {
              // this.$message.error(res&&res.msg);
            }
          });
        }
        // 自动班结
        if (this.autoData.isAuto) {
          let dateList = [];
          this.autoData.automaticClassInfos.forEach((item) => {
            item.dateList.forEach((date) => {
              if (date.time != "") {
                date.time = date.time;
                dateList.push(date.time);
              }
            });
            item.knotTimes = dateList;
            dateList = [];
          });
        }
        let autoData = JSON.parse(JSON.stringify(this.autoData));
        autoData.isAuto = autoData.isAuto ? 1 : 0;
        if (
          autoData.automaticClassInfos &&
          this.stationIdSet(autoData.automaticClassInfos)
        ) {
          setAutomaticClass(autoData).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res&&res.msg);
            } else {
              this.$message.error(res&&res.msg);
            }
          });
        } else {
          this.$message.error("请删除重复油站！！！");
        }
        // 员工账号数据
        if (this.radio == undefined) {
          this.$message.warning("请选择员工账号显示数据");
        } else {
          editHomePageBanjieSettingApi({ employeeShow: this.radio }).then(
            (res) => {
              if (res && res.code == 200) {
                this.$message.success(res && res.msg);
              }
            }
          );
        }
        // 更新首页查询时间设置
        homePageTimeSettingApi(homeParams).then((res) => {
          // this.$message.success("更新首页查询时间设置成功");
          this.getHomePageTimeSetting();
        });
      });
    },

    stationIdSet(automaticClassInfos) {
      const newArr = automaticClassInfos.map((item) => item.stationId);
      const arrSet = new Set(newArr);
      return arrSet.size == newArr.length;
    },

    handleChangeIsAuto(val) {
      if (!val) {
        this.$confirm(
          "是否确认关闭，关闭之后再开启班结设置数据将初始化！！！",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then((res) => {
          if (val) {
            this.autoData = {
              isAuto: true,
              automaticClassInfos: [
                {
                  stationId: "",
                  dateList: [
                    {
                      time: "",
                    },
                  ],
                },
              ],
            };
          } else {
            this.autoData = {
              isAuto: false,
              automaticClassInfos: [],
            };
          }
        });
      } else {
        if (val) {
          this.autoData = {
            isAuto: true,
            automaticClassInfos: [
              {
                stationId: "",
                dateList: [
                  {
                    time: "",
                  },
                ],
              },
            ],
          };
        } else {
          this.autoData = {
            isAuto: false,
            automaticClassInfos: [],
          };
        }
      }
    },

    /**
     * 添加油站块
     */
    handleAddStation() {
      this.autoData.automaticClassInfos.push({
        stationId: "",
        dateList: [
          {
            time: "",
          },
        ],
      });
      this.$nextTick(() => {
        let scrollEl = this.$refs.stationBox;
        scrollEl.scrollTo({ top: scrollEl.scrollHeight, behavior: "smooth" });
      });
    },

    /**
     *
     * @param {Number} index 油站块下标
     */
    handleDeleteStation(index) {
      this.autoData.automaticClassInfos.splice(index, 1);
    },

    /**
     *
     * @param {Number} index 油站块下标
     * @param {Number} dateIndex 班结时间数组下标
     */
    handleAddDate(index, dateIndex) {
      if (dateIndex === 4)
        return this.$message.error("每个油站最多添加五个班结时间！！！");
      this.autoData.automaticClassInfos[index].dateList.push({
        time: "",
      });
    },

    /**
     *
     * @param {Number} index 油站块下标
     * @param {Number} dateIndex 班结时间数组下标
     */
    handleDeleteDate(index, dateIndex) {
      this.autoData.automaticClassInfos[index].dateList.splice(dateIndex, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.station_box {
  display: grid;
  grid-template-columns: repeat(2, 50%);
  // grid-template-rows: repeat(10, 250px);
  grid-row-gap: 20px;
  grid-column-gap: 30px;
  padding: 20px;
  // margin-bottom: 60px;
  overflow-y: scroll;
  height: calc(100vh - 190px);

  .station_item {
    height: fit-content;
    margin-top: 20px;
    display: flex;
    flex-direction: row;
    position: relative;

    .left_item {
      width: 70%;
      height: fit-content;
      padding: 10px;
      border: 1px solid #333;
      border-radius: 10px;

      .title {
        display: inline-block;
        font-weight: 600;
      }
    }

    .right_item {
      width: 30%;
      position: absolute;
      top: 50%;
      right: 0;
      text-align: center;
    }
  }
}

// 首页时间设置css
.timeSetting {
  margin-top: 20px;
  margin-bottom: 30px;
  padding-left: 20px;
  .el-checkbox-button {
    margin-right: 20px;
    border-left: 1px solid #dcdfe6;
    border-radius: 0 4px 4px 0;
  }
}
// 选中且被禁用的按钮
::v-deep .el-checkbox-button.is-disabled .el-checkbox-button__inner {
  background: #409eff;
  color: #fff;
}

.bottom_box {
  border-top: 1px solid #ccc;
  // position: absolute;
  // bottom: 0;
  width: 100%;
  height: 60px;
  background: #fff;
  display: flex;
  justify-content: left;
  align-items: center;
  padding: 0 20px;
}
.t {
  &::before {
    content: "*";
    color: red;
    margin-right: 5px;
  }
}
.ml8 {
  margin-left: 8px;
}
.title1 {
  font-size: 12px;
  font-weight: normal;
  margin-right: 20px;
}
</style>
